package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Destination;
import cn.wolfcode.wolf2w.domain.StrategyCatalog;
import cn.wolfcode.wolf2w.query.StrategyCatalogQueryObject;
import cn.wolfcode.wolf2w.redis.service.IRedisService;
import cn.wolfcode.wolf2w.repository.StrategyCatalogRepository;
import cn.wolfcode.wolf2w.service.IDestinationService;
import cn.wolfcode.wolf2w.service.IRegionService;
import cn.wolfcode.wolf2w.service.IStrategyCatalogService;
import cn.wolfcode.wolf2w.util.DBHelper;
import cn.wolfcode.wolf2w.vo.CatalogVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class StrategyCatalogServiceImpl implements IStrategyCatalogService {

    @Autowired
    private StrategyCatalogRepository strategyCatalogRepository;
    @Autowired
    private IRedisService redisService;
    @Autowired
    private IRegionService regionService;

    @Autowired
    private MongoTemplate template;

    @Autowired
    private IDestinationService destinationService;

    @Override
    public void insert(StrategyCatalog strategyCatalog) {
        strategyCatalogRepository.insert(strategyCatalog);
        strategyCatalog.setId(null);
    }

    @Override
    public void delete(String id) {
        strategyCatalogRepository.deleteById(id);
    }

    @Override
    public void update(StrategyCatalog strategyCatalog) {
        strategyCatalogRepository.save(strategyCatalog);
    }

    @Override
    public StrategyCatalog selectOne(String id) {
        StrategyCatalog strategyCatalog = strategyCatalogRepository.findById(id).orElse(null);
        //StrategyCatalog strategyCatalog = byId.get();
        return strategyCatalog;
    }

    @Override
    public List<StrategyCatalog> selectAll() {
        List<StrategyCatalog> all = strategyCatalogRepository.findAll();
        return all;
    }

    //@Override
    //public List<StrategyCatalog> getDestByRegionId(String rid) {
    //    //1、通过区域id查询区域对象
    //    Region region = regionService.selectOne(rid);
    //    //2、从区域对象上获取目的地id的集合
    //    List<String> refIds = region.getRefIds();
    //    //3、将目的地id的集合转换成目的地名称的集合
    //    List<StrategyCatalog> strategyCatalogs = strategyCatalogRepository.findByIdIn(refIds);
    //    return strategyCatalogs;
    //}

    @Override
    public Page<StrategyCatalog> query(StrategyCatalogQueryObject q) {
        //1、创建查询对象
        Query query=new Query();
        ////2、判断keyword是否为空，若不为空，则进行条件的拼接
        //if(StringUtils.hasLength(q.getKeyword())){
        //    query.addCriteria(Criteria.where("name").regex(q.getKeyword()));//进行拼接高级查询条件时需要使用regex
        //}
        ////判断父亲id长度是否为空，若为空，拼接成null
        //if(!StringUtils.hasLength(q.getParentId())){
        //    query.addCriteria(Criteria.where("parentId").is(null));
        //}else{
        //    query.addCriteria(Criteria.where("parentId").is(q.getParentId()));
        //}
        //3、添加分页语句
        Pageable pageable = PageRequest.of(q.getCurrentPage()-1, q.getPageSize(), Sort.Direction.DESC, "_id");
        Page<StrategyCatalog> page = DBHelper.query(q,query, StrategyCatalog.class, template, pageable);
        return page;
    }

    @Override
    public void saveOrUpdate(StrategyCatalog strategyCatalog) {
        //在保存之前需要将目的地的名称查询出来
        String destId = strategyCatalog.getDestId();
        Destination destination = destinationService.selectOne(destId);
        String name = destination.getName();
        strategyCatalog.setDestName(name);
        if(StringUtils.hasLength(strategyCatalog.getId())){
            this.update(strategyCatalog);
        }else {
            ////在保存之前需要将目的地的名称查询出来
            //String destId = strategyCatalog.getDestId();
            //Destination destination = destinationService.selectOne(destId);
            //String name = destination.getName();
            //strategyCatalog.setDestName(name);
            this.insert(strategyCatalog);
        }
    }

    @Override
    public List<CatalogVO> queryByDestAndCatalog() {
        //List<CatalogVO> list = new ArrayList<>();
        ////聚合查询
        //TypedAggregation<StrategyCatalog> agg = Aggregation.newAggregation(StrategyCatalog.class,
        //        Aggregation.group("destName").
        //                push("name").as("names").
        //                push("id").as("ids")
        //);
        //AggregationResults<Map> result = template.aggregate(agg,Map.class);
        //List<Map> datas = result.getMappedResults(); //将结果转化成list<map>   map描述一行数据
        //for (Map data : datas) {
        //    CatalogVO vo = new CatalogVO();
        //
        //    vo.setDestName(data.get("_id").toString());  //id
        //    List<Object> names = (List<Object>) data.get("names");  //攻略分类的名称集合
        //    List<Object> ids = (List<Object>) data.get("ids");  //攻略分类的ids集合
        //
        //    List<StrategyCatalog> catalogList = new ArrayList<>(); //攻略分类对象
        //
        //    for(int i = 0;i < names.size(); i++){
        //        StrategyCatalog sc = new StrategyCatalog();
        //        String name = names.get(i).toString();
        //        String id = ids.get(i).toString();
        //        sc.setId(id);
        //        sc.setName(name);
        //        catalogList.add(sc);
        //    }
        //    vo.setCatalogList(catalogList);
        //    list.add(vo);
        //}
        //return list;

        //方式2：先查询出所有的攻略分类表中的目的地名称并去重，再以目的地名称为条件去查询该目的地下的攻略分类信息
        List<StrategyCatalog> s=strategyCatalogRepository.findAll();
        List<String> destNames=new ArrayList<>();
        for(StrategyCatalog s1:s){
            destNames.add(s1.getDestName());
        }
        //新建一个集合用来装去重后的数据
        List<String> newDestNames=new ArrayList<>();
        //再将destNames集合中的数据进行去重
        for(String destName:destNames){
            if(!(newDestNames.contains(destName))){
                newDestNames.add(destName);
            }
        }
        //然后以查询出来的目的地名称为条件进行查询相关的攻略分类信息
        ////新建一个集合，封装攻略分类的名称
        //List<String> sns=new ArrayList<>();
        //新建一个集合，封装下拉框的数据信息
        List<CatalogVO> list=new ArrayList<>();
        for(String destName:newDestNames){
            List<StrategyCatalog> strategyCatalogs = strategyCatalogRepository.queryByDestName(destName);
            //将数据封装到CatalogVO中
            CatalogVO catalogVO=new CatalogVO();
            catalogVO.setDestName(destName);
            catalogVO.setCatalogList(strategyCatalogs);
            list.add(catalogVO);
        }
        //再将数据结果返回回去
        return list;
    }

    @Override
    public List<StrategyCatalog> queryByCatalog(String destId) {
        List<StrategyCatalog> list=strategyCatalogRepository.queryByDestId(destId);
        return list;
    }


}
